package com.lznAdmin.base.common.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "lznadmin.jwt")
@Slf4j
public class JwtUtil {

    private static final String JwtNameSpace = "JWT:overdue:";


    @Autowired
    RedisUtil redisUtil;

    // Logger logger = LoggerFactory.getLogger(getClass());
    private long expire;
    private String secret;
    private String header;

    // 生成jwt
    public String generateToken(String username) {

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)// 7天過期
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public String generateToken(String username, long jwtTime) {

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * jwtTime);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)// 7天過期
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // 解析jwt
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            return e.getClaims();
        } catch (Exception e) {
            log.error(e.getMessage());
            // throw new JwtException(e.getMessage());
            return null;
        }
    }

    // jwt是否过期
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

    // jwt是否在登录名单
    public boolean isLoginList(String jwt) {
        Claims claimByToken = getClaimByToken(jwt);
        String userName = claimByToken.getSubject();
        boolean b = redisUtil.hasKey("JWT:loginList:" + userName);
        if (b) {
            Object jwtLogin = redisUtil.get("JWT:loginList:" + userName);
            return jwtLogin.equals(jwt);
        }
        return false;
    }

    // jwt登录名单
    public boolean loginList(String jwt) {
        Claims claim = this.getClaimByToken(jwt);
        DateTime now = DateTime.now();
        long between = DateUtil.between(now, claim.getExpiration(), DateUnit.SECOND, false);
        log.info("现在={}，jwt到期={}", DateTime.now(), DateUtil.formatDateTime(claim.getExpiration()));
        log.info("{}秒", between);
        if (between > 1) {
            log.info(String.valueOf(redisUtil.get(jwt)));
            log.info(String.valueOf(redisUtil.getExpire(jwt)));
            return redisUtil.set("JWT:loginList:" + claim.getSubject(), jwt, between);
        }
        return false;
    }

    // 从登录名单中删除
    public boolean delLoginList(String username) {

        if (redisUtil.hasKey("JWT:loginList:" + username)) {
            redisUtil.del("JWT:loginList:" + username);
            return true;
        }
        return false;
    }

}
